package com.csea;

import java.util.*;

/**
 * Lambda 和 Stream 性能
 *
 * @author Csea
 * @title
 * @date 2019/12/12 21:06
 */
public class Test2 {
    public static void main(String[] args) {
        Random random = new Random();

        List<Integer> integerList = new ArrayList<>();

        for (int i = 0; i < 1000000; i++) {
            integerList.add(random.nextInt(Integer.MAX_VALUE));
        }

        // 1.stream
        testStream(integerList);
        // 2.parallelStream
        testParallelStream(integerList);
        // 3.普通for
        testForLoop(integerList);
        // 4.增强型for
        testStrongForLoop(integerList);
        // 5. 迭代器
        testInterator(integerList);
    }

    public static void testStream(List<Integer> list) {
        long start = System.currentTimeMillis();
        Optional optional = list.stream().max(Integer::compare);
        System.out.println(optional.get());
        long end = System.currentTimeMillis();
        System.out.println("testStream：" + (end - start) + "ms");
    }

    public static void testParallelStream(List<Integer> list) {
        long start = System.currentTimeMillis();
        Optional optional = list.parallelStream().max(Integer::compare);
        System.out.println(optional.get());
        long end = System.currentTimeMillis();
        System.out.println("testParallelStream：" + (end - start) + "ms");
    }

    public static void testForLoop(List<Integer> list) {
        long start = System.currentTimeMillis();
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < list.size(); i++) {
            int current = list.get(i);
            if (current > max) {
                max = current;
            }
        }
        System.out.println(max);
        long end = System.currentTimeMillis();
        System.out.println("testForLoop：" + (end - start) + "ms");
    }

    public static void testStrongForLoop(List<Integer> list) {
        long start = System.currentTimeMillis();
        int max = Integer.MIN_VALUE;
        for (Integer integer : list) {
            if (integer > max) {
                max = integer;
            }
        }
        System.out.println(max);
        long end = System.currentTimeMillis();
        System.out.println("testStrongForLoop：" + (end - start) + "ms");
    }

    public static void testInterator(List<Integer> list) {
        long start = System.currentTimeMillis();
        Iterator<Integer> it = list.iterator();
        int max = it.next();
        while (it.hasNext()) {
            int current = it.next();
            if (current > max) {
                max = current;
            }
        }
        System.out.println(max);
        long end = System.currentTimeMillis();
        System.out.println("testInterator：" + (end - start) + "ms");
    }
}
